<template>
  <div class="details">
    <div class="tabs">
      <button :class="{active: tab==='detail'}" @click="tab='detail'">详情</button>
      <button :class="{active: tab==='log'}" @click="tab='log'">日志</button>
      <span class="spacer"></span>
      <button class="close-btn" @click="emit('close')">关闭</button>
    </div>
    <div class="content" v-if="tab==='detail'">
      <div class="kv-grid">
        <div class="item">
          <div class="label">名称</div>
          <div class="value ellipsis" :title="task?.name">{{ task?.name || '-' }}</div>
        </div>
        <div class="item">
          <div class="label">类型</div>
          <div class="value"><span class="badge type">{{ typeLabel }}</span></div>
        </div>
        <div class="item">
          <div class="label">状态</div>
          <div class="value">
            <span class="badge" :class="'status-'+(task?.status||'unknown')">{{ task?.status || '-' }}</span>
          </div>
        </div>
        <div class="item">
          <div class="label">速度</div>
          <div class="value">{{ formatSpeed(task?.speed) }}</div>
        </div>
        <div class="item">
          <div class="label">进度</div>
          <div class="value">
            <div class="progress-line">
              <div class="bar" :style="{ width: ((task?.progress||0)+'%') }"></div>
            </div>
            <div class="muted">{{ formatSize(task?.downloaded) }} / {{ formatSize(task?.size) }}</div>
          </div>
        </div>
        <div class="item">
          <div class="label">剩余时间</div>
          <div class="value">{{ formatETA(task?.eta) }}</div>
        </div>
        <div class="item path">
          <div class="label">保存路径</div>
          <div class="value mono ellipsis" :title="task?.savePath">{{ task?.savePath || '-' }}</div>
        </div>
        <div class="item" v-if="task?.type==='bt'">
          <div class="label">做种</div>
          <div class="value">{{ seedingLabel }}</div>
        </div>
        <div class="item">
          <div class="label">重试次数</div>
          <div class="value">{{ task?.retryCount || 0 }}</div>
        </div>
      </div>

      <div class="actions">
        <button class="btn" @click="onOpenInFolder" :disabled="!task">📂 打开所在目录</button>
        <button class="btn btn-ghost" @click="onCopyLink" :disabled="!task">🔗 复制下载链接</button>
        <button class="btn btn-warning" @click="onRename" :disabled="!task || task.status==='downloading'">✏️ 重命名</button>
      </div>
    </div>
    <div class="content" v-else>
      <div v-if="logs.length" class="log-container">
        <div class="log-row" v-for="(entry, idx) in logs" :key="idx">
          <span class="log-time">{{ formatTime(entry.time) }}</span>
          <span class="log-level" :class="'lv-'+entry.level">{{ entry.level }}</span>
          <span class="log-msg">{{ entry.message }}</span>
        </div>
      </div>
      <div v-else class="empty-state">
        <div class="title">暂无日志</div>
        <div class="desc">当任务开始、暂停、失败等事件发生时，会在此显示详细信息。</div>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import * as Manager from '../../wailsjs/go/main/Manager.js'
import { EventsOn } from '../../wailsjs/runtime/runtime.js'
const props = defineProps({ task: { type: Object, default: null }, settings: { type: Object, default: () => ({}) } })
const emit = defineEmits(['set-category','close'])
const tab = ref('detail')
const category = ref('')
const logs = ref([])

watch(() => props.task?.category, (v) => { category.value = v || '' }, { immediate: true })

watch(() => props.task?.id, async (id) => {
  if (!id) { logs.value = []; return }
  await loadLogs(id)
}, { immediate: true })

EventsOn && EventsOn('tasks:update', async () => {
  if (props.task?.id) {
    await loadLogs(props.task.id)
  }
})

async function loadLogs(id){
  try {
    const items = await Manager.GetTaskLogs(id)
    logs.value = (items || []).map(x => ({
      time: x.time || x.Time, // 兼容字段命名
      level: x.level || x.Level,
      message: x.message || x.Message
    }))
  } catch (e) { /* noop */ }
}

function onSaveCategory(){
  emit('set-category', category.value || '')
}

function formatTime(v){
  try {
    const d = typeof v === 'string' ? new Date(v) : new Date(v.seconds ? v.seconds*1000 : v)
    const pad = (n)=>String(n).padStart(2,'0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch { return '' }
}

async function onOpenInFolder(){
  if (!props.task) return
  try { await Manager.OpenInFolder(props.task.id) } catch (e) { console.error(e) }
}

async function onCopyLink(){
  if (!props.task?.url) return
  try {
    await navigator.clipboard.writeText(props.task.url)
  } catch (e) {
    console.error(e)
  }
}

async function onRename(){
  if (!props.task) return
  const base = props.task.name || ''
  const v = window.prompt('输入新的文件名：', base)
  if (!v || v === base) return
  try { await Manager.Rename(props.task.id, v) } catch (e) { console.error(e) }
}

function formatSpeed(v){
  if (!v || v <= 0) return '-'
  const units = ['B/s','KB/s','MB/s','GB/s']
  let i = 0
  let x = v
  while (x >= 1024 && i < units.length-1){ x/=1024; i++ }
  return x.toFixed(1)+' '+units[i]
}
function formatSize(v){
  if (!v || v <= 0) return '0 B'
  const units = ['B','KB','MB','GB','TB']
  let i = 0
  let x = v
  while (x >= 1024 && i < units.length-1){ x/=1024; i++ }
  return x.toFixed(1)+' '+units[i]
}
function formatETA(s){
  if (!s || s <= 0) return '-'
  const h = Math.floor(s/3600)
  const m = Math.floor((s%3600)/60)
  const sec = Math.floor(s%60)
  return (h? (String(h).padStart(2,'0')+':'):'')+String(m).padStart(2,'0')+':'+String(sec).padStart(2,'0')
}

const typeLabel = computed(() => props.task?.type || 'http')
const seedingLabel = computed(() => {
  if (!props.task || props.task.type !== 'bt') return '-'
  const completed = props.task.status === 'completed'
  if (!completed) return '未完成'
  return props.settings?.btKeepSeeding ? '做种中' : '未做种'
})
</script>

<style scoped>
.details {
  height: 220px;
  display: grid;
  grid-template-rows: 36px 1fr;
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  overflow: hidden;
  margin-top: 8px;
}
.tabs {
  display: flex;
  gap: 6px;
  align-items: center;
  padding: 0 10px;
}
.tabs .spacer { flex: 1; }
.tabs .close-btn { margin-left: auto; padding: 4px 8px; border: 1px solid rgba(255,255,255,0.12); border-radius: 6px; background: transparent; color:#e6e6e6; font-size:12px; }
.tabs .close-btn:hover { background: rgba(255,255,255,0.06); }
.tabs button {
  padding: 4px 8px;
  background: transparent;
  border: 1px solid rgba(255,255,255,0.12);
  border-radius: 6px;
  color: #e6e6e6;
  font-size: 12px;
}
.tabs button.active, .tabs button:hover {
  background: rgba(255,255,255,0.06);
}
.tabs { border-bottom: 1px solid var(--border-color); }
.content {
  padding: 8px 10px;
  overflow: auto;
  white-space: pre-wrap;
}
.row { display:flex; gap:6px; align-items:center; margin-top:6px; }
.actions { display:flex; gap:6px; margin-top:8px; }

/* Beautified details */
.kv-grid {
  display: grid;
  grid-template-columns: 110px 1fr 110px 1fr;
  gap: 6px 12px;
  margin-bottom: 6px;
}
.kv-grid .item { display: contents; }
.kv-grid .label { 
  color: var(--text-secondary, #bdbdbd);
  font-size: 12px; 
}
.kv-grid .value {
  font-size: 12.5px;
}
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }
.ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.muted { opacity: 0.8; font-size: 12px; margin-top: 3px; }

.badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 999px;
  font-size: 12px;
  background: rgba(255,255,255,0.08);
  border: 1px solid rgba(255,255,255,0.12);
}
.badge.type { background: rgba(100, 181, 246, 0.15); border-color: rgba(100,181,246,0.35); }
.badge.status-downloading { background: rgba(76,175,80,0.15); border-color: rgba(76,175,80,0.35); }
.badge.status-paused { background: rgba(255,152,0,0.15); border-color: rgba(255,152,0,0.35); }
.badge.status-completed { background: rgba(33,150,243,0.15); border-color: rgba(33,150,243,0.35); }
.badge.status-failed { background: rgba(244,67,54,0.15); border-color: rgba(244,67,54,0.35); }

.progress-line { height: 4px; background: rgba(255,255,255,0.08); border-radius: 4px; overflow: hidden; }
.progress-line .bar { height: 100%; background: linear-gradient(90deg, #4da3ff, #6be7ff); }

/* Logs */
.log-container { 
  display: grid; 
  gap: 4px; 
  max-height: 100%; 
}
.log-row { display:flex; gap:6px; align-items:center; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.06); border-radius:6px; padding:4px 6px; font-size:12px; }
.log-time { opacity:0.7; font-family: ui-monospace, Menlo, Monaco, Consolas, "Courier New", monospace; }
.log-level { text-transform: uppercase; font-weight:600; }
.log-level.lv-info { color:#64b5f6; }
.log-level.lv-warning { color:#ffb74d; }
.log-level.lv-error { color:#ef5350; }
.log-msg { white-space: pre-wrap; }
.empty-state { 
  display: grid; 
  gap: 4px; 
  align-content: center; 
  justify-items: start; 
  height: 100%; 
  color: var(--text-secondary, #bdbdbd); 
}
.empty-state .title { font-weight: 600; color: var(--text-color, #e6e6e6); }
.empty-state .desc { font-size: 12px; }

/* Action buttons */
.actions { display:flex; gap:8px; margin-top:8px; }
.actions .btn { height:28px; padding:0 10px; border-radius:6px; border:1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.06); color:#e6e6e6; font-size:12px; display:inline-flex; align-items:center; gap:6px; }
.actions .btn:hover { background: rgba(255,255,255,0.12); }
.actions .btn:disabled { opacity:.6; cursor:not-allowed; }
.actions .btn-ghost { background: transparent; border-color: rgba(255,255,255,0.12); }
.actions .btn-ghost:hover { background: rgba(255,255,255,0.06); }
.actions .btn-warning { background: #ffb300; border-color:#ffb300; color:#1a2327; }
.actions .btn-warning:hover { background:#ffa000; border-color:#ffa000; }
</style>
